package dk.modified.reshary;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ViewPagerFragment extends Fragment {

	private GifImageView imageView;
	private Owners owner;
	private ImageButton cmd_video_play;

	private byte[] gifBytes;
	private Boolean gifIsPlaying = false;
	private long timeOnPress;
	private float xOnPressed;
	private float yOnPressed;

	private Boolean bottomBarIsVisible = true;
	private int actionBarHeight;
	private int bottomBarHeight;

	private onSetBottomBarHidden mOnSetBottomBarHidden;

	private ProgressBar progressBar;
	private Boolean isFavorite;

	public static ViewPagerFragment newInstance(Owners owner,
			int actionBarHeight, int bottomBarHeight) {

		ViewPagerFragment pageFragment = new ViewPagerFragment();
		Bundle bundle = new Bundle();
		bundle.putParcelable("owner", owner);
		bundle.putInt("actionBar", actionBarHeight);
		bundle.putInt("bottomBar", bottomBarHeight);
		pageFragment.setArguments(bundle);

		return pageFragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.layout_view_pager, container, false);

		Bundle b = getArguments();
		owner = b.getParcelable("owner");
		actionBarHeight = b.getInt("actionBar");
		bottomBarHeight = b.getInt("bottomBar");
		progressBar = (ProgressBar) v.findViewById(R.id.prgbar);
		progressBar.setVisibility(View.VISIBLE);

		imageView = (GifImageView) v.findViewById(R.id.imageview);
		registerForContextMenu(imageView);

		if (getActivity().getIntent().getExtras().containsKey("favorite")) {
			isFavorite = true;
		} else {
			isFavorite = false;
		}

		PabloPicasso.with(getActivity()).load(owner.getFilename())
				.into(imageView, new Callback() {

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						if (owner.getMediaState() == Owners.STATE_GIF
								|| owner.getMediaState() == Owners.STATE_VIDEO) {
							cmd_video_play.setVisibility(View.VISIBLE);
						}
						progressBar.setVisibility(View.GONE);
					}

					@Override
					public void onError() {
						progressBar.setVisibility(View.GONE);
					}
				});

		imageView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					xOnPressed = event.getRawX();
					yOnPressed = event.getRawY();
					timeOnPress = System.currentTimeMillis();
				}

				if (event.getAction() == MotionEvent.ACTION_UP) {

					long diff = System.currentTimeMillis() - timeOnPress;

					if (diff < 300 && event.getPointerCount() == 1) {
						if (Util.calculateDifference(xOnPressed,
								event.getRawX()) < 10
								|| Util.calculateDifference(yOnPressed,
										event.getRawY()) < 10) {
							if (owner.getMediaState() == Share.STATE_GIF) {
								if (gifIsPlaying) {
									imageView.stopAnimation();

									cmd_video_play.setVisibility(View.VISIBLE);
									gifIsPlaying = false;
								} else {
									setBottomBarVisibility(event);
								}
							} else {
								setBottomBarVisibility(event);
							}

						}
					}

				}

				return false;
			}
		});

		cmd_video_play = (ImageButton) v.findViewById(R.id.cmd_video_play);
		cmd_video_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (owner.getVideoFilename() != null) {

					if (owner.getMediaState() == Owners.STATE_VIDEO) {
						Intent i = new Intent(getActivity()
								.getApplicationContext(), VideoActivity.class);
						i.putExtra("videofilename", owner.getVideoFilename());
						getActivity().startActivity(i);
					} else if (owner.getMediaState() == Owners.STATE_GIF) {
						DownloadGif(owner.getVideoFilename());
					}

				} else {
					Toast.makeText(
							getActivity().getApplicationContext(),
							getActivity().getString(R.string.video_unavailable),
							Toast.LENGTH_LONG).show();
				}
			}
		});

		return v;

	}

	private void setBottomBarVisibility(MotionEvent event) {

		if (bottomBarIsVisible) {

			float yAxisValue = event.getAxisValue(MotionEvent.AXIS_Y);
			if (yAxisValue + actionBarHeight < imageView.getHeight()
					- bottomBarHeight) {
				if (mOnSetBottomBarHidden != null) {
					mOnSetBottomBarHidden.hide();
				}
				bottomBarIsVisible = false;
			}
		} else {
			if (mOnSetBottomBarHidden != null) {
				mOnSetBottomBarHidden.show();
			}
			bottomBarIsVisible = true;
		}
	}

	private void DownloadGif(String filename) {

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		cmd_video_play.setVisibility(View.GONE);
		if (gifBytes != null) {
			imageView.startAnimation();
			gifIsPlaying = true;
		}

		else {
			imageView.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);

			ResharyRestClient.downloadImage(filename, null,
					new BinaryHttpResponseHandler(allowedContentTypes) {

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] binaryData, Throwable error) {

							Log.d("DEBUG", error.toString());
						}

						@Override
						public void onSuccess(byte[] binaryData) {
							
							try{
								gifBytes = binaryData;

								imageView.startAnimation();
								imageView.setBytes(gifBytes);

								gifIsPlaying = true;

								progressBar.setVisibility(View.GONE);
								imageView.setVisibility(View.VISIBLE);
							}
							catch (Exception e){
								progressBar.setVisibility(View.GONE);
								imageView.setVisibility(View.VISIBLE);
								gifIsPlaying = false;
								gifBytes = null;
								Toast.makeText(getActivity(), getString(R.string.gif_error), Toast.LENGTH_LONG).show();
							}

						}

					}, getActivity(), null);

		}

	}

	public void setOnBottomBarHiddenListener(onSetBottomBarHidden listener) {
		mOnSetBottomBarHidden = listener;
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub

		if (imageView != null) {
			imageView.stopAnimation();
			imageView.clear();
		}
		gifBytes = null;
		gifIsPlaying = false;

		super.onDestroyView();
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub

		if (imageView != null) {
			if (imageView.isAnimating()) {
				if (!isVisibleToUser) {
					imageView.stopAnimation();
					if (owner.getMediaState() == Owners.STATE_GIF) {
						if (cmd_video_play != null) {
							cmd_video_play.setVisibility(View.VISIBLE);
						}
					}
				}
			}

		}

		super.setUserVisibleHint(isVisibleToUser);

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);

		MenuItem cmd_favorite = menu.findItem(R.id.cmd_favorite);
		if (isFavorite)
			cmd_favorite.setTitle(getString(R.string.context_favorite_remove));
		else
			cmd_favorite
					.setTitle(getString(R.string.context_favorite_add_or_remove));
		MenuItem cmd_save = menu.findItem(R.id.cmd_save);
		if (owner.getMediaState() == Owners.STATE_GIF)
			cmd_save.setTitle(getString(R.string.save_gif));
		else
			cmd_save.setTitle(getString(R.string.save_image));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		if (getUserVisibleHint()) {
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
					.getMenuInfo();

			switch (item.getItemId()) {
			case R.id.cmd_favorite:
				if (isFavorite) {
					RemoveFromFavorite(Integer.parseInt(owner.getId()));
					// adapter.remove(owner);
				} else {
					AddToFavorite(Integer.parseInt(owner.getId()));
				}
				break;
			case R.id.cmd_save:
				if (owner.getMediaState() == Owners.STATE_GIF) {
					if (gifBytes != null) {
						File tempFile = Util.saveGif(gifBytes);
						if (tempFile != null) {
							Bitmap tempBitmap = BitmapFactory.decodeByteArray(
									gifBytes, 0, gifBytes.length);
							SaveMediaNotification saveNotification = new SaveMediaNotification(
									getActivity(), tempBitmap,
									owner.getMediaState(),
									Uri.fromFile(tempFile));
							saveNotification.createNotification();
						} else {
							DownloadGifBeforeSave(owner.getVideoFilename());
						}
					} else {
						DownloadGifBeforeSave(owner.getVideoFilename());
					}

				}

				else {

					Runnable r = new Runnable() {

						@Override
						public void run() {
							final BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView
									.getDrawable();
							final Bitmap yourBitmap = bitmapDrawable
									.getBitmap();

							File tempFile = Util.saveImage(yourBitmap);
							if (tempFile != null) {
								SaveMediaNotification saveNotification = new SaveMediaNotification(
										getActivity(), yourBitmap,
										owner.getMediaState(),
										Uri.fromFile(tempFile));
								saveNotification.createNotification();
							}
						}

					};
					new Thread(r).start();
//
//					DownloadImageBeforeSave(owner.getFilename());
				}

			default:
				return super.onContextItemSelected(item);
			}
		} else
			return false; // Pass the event to the next fragment

		return true;
	}

	public void AddToFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("add_favorite/", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_add);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
					}

				}, getActivity());

	}

	public void RemoveFromFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("rem_favorite/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_remove);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
					}

				}, getActivity());

	}

	private void DownloadGifBeforeSave(String filename) {

		final DownloadNotification notificationDownload = new DownloadNotification(
				getActivity());
		notificationDownload.createNotification();

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		ResharyRestClient.downloadImage(filename, null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {

						Toast.makeText(getActivity(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {
						int progressPercentage = (int) 100 * bytesWritten
								/ totalSize;
						if (progressPercentage % 5 == 0)
							notificationDownload
									.setProgress(progressPercentage);
					}

					@Override
					public void onSuccess(byte[] binaryData) {
						notificationDownload.completed();
						
						try{
							File tempFile = Util.saveGif(binaryData);
							if (tempFile != null) {

								Bitmap tempBitmap = BitmapFactory.decodeByteArray(
										binaryData, 0, binaryData.length);
								SaveMediaNotification saveNotification = new SaveMediaNotification(
										getActivity(), tempBitmap, owner
												.getMediaState(), Uri
												.fromFile(tempFile));
								saveNotification.createNotification();
							}
						} 
						catch (Exception e){
							Toast.makeText(getActivity(), getString(R.string.gif_error), Toast.LENGTH_LONG).show();
						}

					}

				}, getActivity(), null);
	}

	private void DownloadImageBeforeSave(String filename) {
		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		ResharyRestClient.downloadImage(filename, null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {

						Toast.makeText(getActivity(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(final byte[] binaryData) {
						Runnable r = new Runnable() {
							@Override
							public void run() {

								Bitmap myTempBitmap = BitmapFactory
										.decodeByteArray(binaryData, 0,
												binaryData.length);

								File tempFile = Util.saveImage(myTempBitmap);
								if (tempFile != null) {
									SaveMediaNotification saveNotification = new SaveMediaNotification(
											getActivity(), myTempBitmap, owner
													.getMediaState(), Uri
													.fromFile(tempFile));
									saveNotification.createNotification();
								}
							}
						};
						new Thread(r).start();
					}

				}, getActivity(), null);
	}

}
